import axios from "axios";

export const req = (url: string, data = {}, method = "get") => {
  return new Promise((resolve, reject) => {
    let requ = new Function();
    if (method === "post") {
      requ = axios({
        method: method === "post" ? "POST" : "",
        url,
        data,
        //params: data,
      });
    } else {
      requ = axios.get(url, { params: data });
    }
    requ
      .then((data) => {
        if (data.status >= 200 && data.status < 300) {
          data = data.data;
          if (typeof data !== "object" || data == null || !data) {
            reject("服务器返回的格式错误，请与王阳联系");
          }
          if (!data.isSuccess) {
            //console.log(data);
            reject(`错误代码:[${data.code}]` + "\r\n" + `报错信息:${data.msg}`);
          } else {
            if (data.data) {
              resolve(data.data);
            } else {
              reject(`无法获取数据，参考：${JSON.stringify(data)}`);
            }
          }
        } else {
          reject(`HTTP[${data.status}]响应错误`);
        }
      })
      .catch((error) => {
        //console.log(error);
        if (typeof error === "object" && error.code && error.message) {
          reject(
            `错误代码:[${error.code}]\r\n报错信息:${
              error.message
            }\r\n参考信息:${error?.response?.data?.message || "无"}`
          );
        } else {
          reject("" + error);
        }
      });
  });
};

export const formaData = (timer: any) => {
  function pad(timeEl: any, total = 2, str = "0") {
    return timeEl.toString().padStart(total, str);
  }
  const year = timer.getFullYear();
  const month = timer.getMonth() + 1; // 由于月份从0开始，因此需加1
  const day = timer.getDate();
  const hour = timer.getHours();
  const minute = timer.getMinutes();
  const second = timer.getSeconds();
  return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(
    minute
  )}:${pad(second)}`;
};
